package com.likou.second_challenge;

import java.util.ArrayList;
import java.util.List;

public class q54 {

    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;

        int left = 0;
        int right = n - 1;
        int top = 0;
        int down = m - 1;
        List<Integer> ans = new ArrayList<>();

        while (true) {
            // 右
            for (int i = left; i <= right; i++) {
                ans.add(matrix[top][i]);
            }
            if (top >= down) {
                break;
            }
            top++;

            // 下
            for (int i = top; i <= down; i++) {
                ans.add(matrix[i][right]);
            }
            if (right <= left) {
                break;
            }
            right--;

            // 左
            for (int i = right; i >= left; i--) {
                ans.add(matrix[down][i]);
            }
            if (top >= down) {
                break;
            }
            down++;

            // 上
            for (int i = down; i >= top; i--) {
                ans.add(matrix[i][left]);
            }
            if (right <= left) {
                break;
            }
            left++;
        }

        return ans;
    }

}
